-- UITankUse
-- Create by cheny3
-- 罐子使用界面

require "game/ui/form/shop/UITankDesc"
require "game/ui/form/shop/UIGoldenPotBonus"
require "game/ui/form/shop/UIBuyPuzzles";

-- UITankUse继承自Layer
UITankUse = class("UITankUse", function()
    return cc.Layer:create();
end);

function UITankUse.create(tankType, extra)
    return UITankUse.new(tankType, extra);
end

-- 内部函数声明
local useType = {5, 1};
local campType = {4, 3, 1, 2};
local defaultPosY = {-33, 0};
local PredefinedPos = {
    {cc.p(0, 100)},
    {cc.p(-100, 100), cc.p(100, 100)},
    {cc.p(-200, 100), cc.p(0, 100), cc.p(200, 100), cc.p(-100, -100), cc.p(100, -100)},
    {cc.p(-200, 100), cc.p(0, 100), cc.p(200, 100), cc.p(-200, -100), cc.p(0, -100), cc.p(200, -100)},
    {cc.p(-100, 100), cc.p(100, 100), cc.p(-100, -100), cc.p(100, -100)},
};

-- 构造函数
function UITankUse:ctor(tankType, extra)
    -- 初始化
    self:setName("UITankUse");
    -- 复用商城界面
    local node = cc.CSLoader:createNode("layout/market/MarketMain.csb");
    self:addChild(node);
    self.node = node;
    self.tankType = tankType;

    local TOP = node:getChildByName("TOP");
    local scrollview = findChildByName(self.node, "CT/scrollview");
    self.TOP = TOP;
    self.scrollview = scrollview;
    self.scrollview:setVisible(true);

    self.showEffect = true;

    if type(extra) == "table" and extra["camp_id"] ~= nil then
        self.campId = extra["camp_id"];
    end

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollview:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 适配
    self:resize();

    self.initHeight = self.scrollview:getInnerContainerSize().height;

    -- 重绘
    self:redraw();

    -- 叠两层蒙版，隐藏bottom_mask
    local bgNode = node:getChildByName("bg");
    bgNode:loadTexture("images/ui/common/mengban.png");
    local scrollMask = findChildByName(self.node, "CT/bottom_mask");
    scrollMask:setVisible(false);
    local mask = node:getChildByName("mask");

    -- 几个没用的panel直接隐藏
    local bottomPanel = findChildByName(self.node, "CT/bottom_panel");
    local selectPanel = findChildByName(self.node, "CT/select_panel");
    bottomPanel:setVisible(false);
    selectPanel:setVisible(false);
end

-- 适配
function UITankUse:resize()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local node = self.node;

    -- bg/mask居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");
    AlignM.fitToScreen(node, "mask");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- TOP顶部居中并缩放至合适大小
    AlignM.alignToTopCenter(node, "TOP");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");

    local scale = math.min(w / DESIGN_WIDTH, h / DESIGN_HEIGHT);

    -- 设置scroll的新视口高度
    local scrollview = findChildByName(self.node, "CT/scrollview");
    local scrollViewSize = scrollview:getContentSize();

    local height = (h / scale) - 400;
    scrollview:setContentSize(scrollViewSize.width, height);

    -- 动态设置蒙版的位置
    local scrollMask = findChildByName(self.node, "CT/bottom_mask");
    scrollMask:setPosition(scrollMask:getPositionX(), scrollview:getPositionY() - height);
end

-- 重绘
function UITankUse:redraw()
    -- 还原标题高度
    local titleNode = findChildByName(self.node, "TOP/title_node");
    local titleLabel = findChildByName(titleNode, "title");
    local subheadLabel = findChildByName(titleNode, "subhead");
    titleLabel:setPositionY(defaultPosY[2]);
    subheadLabel:setPositionY(defaultPosY[1]);

    if self.tankType == "gem" then
        -- 黄金罐
        self:redrawGoldTank();
    elseif self.tankType == "money" then
        -- 冈布奥的罐
        self:redrawNormalTank();
    elseif self.tankType == "camp" then
        -- 阵营
        self:redrawCamp();
    elseif self.tankType == "pet_camp_card" then
        self:redrawPetCampCard();
    end

    -- 播放效果节点
    local tankNode = findChildByName(self.node, "CT/tank_node");
    tankNode:removeAllChildren();
    tankNode:setVisible(false);
    self.scrollview:setVisible(true);

    -- 按钮显隐
    local btnDesc = findChildByName(self.node, "BT/btn_buy_gem");
    local btnSet = findChildByName(self.node, "BT/btn_set");
    -- 这个按钮会涉及到动作
    btnDesc:stopAllActions();
    btnDesc:setScale(1);
    if self.tankType == "camp" then
        btnDesc:setVisible(true);
        btnSet:setVisible(false);
        btnDesc:setTitleText(getLocStr("btn_text_help"));
    else
        btnDesc:setVisible(true);
        btnDesc:setTouchEnabled(true);
        btnDesc:setBright(true);
        if self.tankType == "gem" then
            btnSet:setVisible(true);
            btnDesc:setTitleText(getLocStr("btn_text_bonus"));
        else
            btnSet:setVisible(false);
            btnDesc:setTitleText(getLocStr("btn_text_help"));
        end
    end
    -- 检查奖励
    self:updateBonusBubble();
end

-- 更新可领取奖励泡泡
function UITankUse:updateBonusBubble()
    local hintNode = findChildByName(self.node, "BT/btn_buy_gem/hint");
    -- 如果可领取奖励
    if self.tankType == "gem" then
        local canGetNum = PetShopM.takePotUseBonusNum(self.campId);
        if canGetNum > 0 then
            checkBlueBubbleStatus(hintNode, canGetNum);
            hintNode:setVisible(true);
        else
            hintNode:setVisible(false);
        end
    else
        hintNode:setVisible(false);
    end
end

-- 绘制阵营
function UITankUse:redrawCamp()
    local titleNode = findChildByName(self.node, "TOP/title_node");
    local titleLabel = findChildByName(titleNode, "title");
    local subheadLabel = findChildByName(titleNode, "subhead");
    subheadLabel:setVisible(false);
    -- 主标题
    TextStyleM.setArtWordTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("choose_camp"));

    -- 绘制每一项
    self:redrawItems();
end

-- 绘制黄金的罐界面
function UITankUse:redrawGoldTank()
    local titleNode = findChildByName(self.node, "TOP/title_node");
    local titleLabel = findChildByName(titleNode, "title");
    local subheadLabel = findChildByName(titleNode, "subhead");

    -- 主标题颜色
    local color;
    if self.campId == 1 then
        color = TextStyleM.TEXT_COLOR_LIGHT_GREEN;
    elseif self.campId == 2 then
        color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;
    elseif self.campId == 3 then
        color = TextStyleM.TEXT_COLOR_LIGHT_YELLOW;
    else
        color = TextStyleM.TEXT_COLOR_LIGHT_RED;
    end

    -- 主标题
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, color, true, -1, nil, nil, nil, nil, true);
    local campName = CampM.query(self.campId, "name");
    titleLabel:setString(campName);

    local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "gem");
    local itemName = ItemM.query(classId, "name");
    local num = ItemM.getAmount(ME.user, classId);

    -- 副标题
    local kerning = -3;
    if not isFullWidthLang() then
        kerning = -1;
    end
    TextStyleM.setTextStyle(subheadLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, getLocKerning() + kerning, nil, nil, nil, nil, true);
    subheadLabel:setString(string.format(getLocStr("item_bonus_format"), itemName, num));
    subheadLabel:setVisible(true);

    -- 标题上移
    titleLabel:setPositionY(defaultPosY[2] + 5);
    subheadLabel:setPositionY(defaultPosY[1] + 5);

    -- 绘制每一项
    self:redrawItems();
end

-- 绘制冈布奥的罐界面
function UITankUse:redrawNormalTank()
    local titleNode = findChildByName(self.node, "TOP/title_node");
    local titleLabel = findChildByName(titleNode, "title");
    local subheadLabel = findChildByName(titleNode, "subhead");
    -- 主标题
    TextStyleM.setArtWordTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("use_number"));

    local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "money");
    local itemName = ItemM.query(classId, "name");
    local num = ItemM.getAmount(ME.user, classId);

    -- 副标题
    local kerning = -3;
    if not isFullWidthLang() then
        kerning = -1;
    end
    TextStyleM.setTextStyle(subheadLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, getLocKerning() + kerning, nil, nil, nil, nil, true);
    subheadLabel:setString(string.format(getLocStr("item_bonus_format"), itemName, num));
    subheadLabel:setVisible(true);

    -- 标题上移
    titleLabel:setPositionY(defaultPosY[2] + 5);
    subheadLabel:setPositionY(defaultPosY[1] + 5);

    -- 绘制每一项
    self:redrawItems();
end

-- 收集项目信息
function UITankUse:getItemsInfo()
    local list = {};

    if self.tankType == "money" then
        for index, useNum in ipairs(useType) do
            local info = {};
            info.type = "money";
            info.useNum = useNum;
            info.index = index;
            table.insert(list, info);
        end
    elseif self.tankType == "camp" then
        for index, campId in ipairs(campType) do
            local info = {};
            info.type = "camp";
            info.campId = campId;
            info.index = index;
            table.insert(list, info);
        end
    elseif self.tankType == "gem" then
        for index, useNum in ipairs(useType) do
            local info = {};
            info.type = "gem";
            info.useNum = useNum;
            info.campId = self.campId;
            info.index = index;
            table.insert(list, info);
        end
    end
    return list;
end

-- 绘制每子一项
function UITankUse:redrawItems()
    local node = cc.CSLoader:createNode("layout/shop/TankUseItem.csb");
    local widget = replaceNodeWithWidget(node);

    local list = self:getItemsInfo();

    self.scrollview:removeAllChildren();

    -- 左边距
    local leftMargin = 20;

    -- 行间距
    local gap = 10;
    local offset = -120;

    -- 单个表项高度
    local widgetHeight = 110;

    local totalNum = #list;
    self.totalNum = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = totalNum * (widgetHeight + gap);
    if totalHeight < self.initHeight then
        startHeight = self.initHeight - totalHeight;
    end

    startHeight = startHeight + offset;

    -- 设置内部滚动区域的高度
    self.scrollview:setInnerContainerSize(cc.size(self.scrollview:getInnerContainerSize().width,
        math.max(totalHeight, self.initHeight)));

    local bg = findChildByName(widget, "bg");
    local bgHeight = bg:getVirtualRenderer():getContentSize().height/2;
    local bgWidth = bg:getVirtualRenderer():getContentSize().width/2;

    self.items = {};

    for i, info in ipairs(list) do
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight + i * (widgetHeight + gap);
        child:setPositionX(bgWidth + x);
        child:setPositionY(bgHeight + y);
        -- 初始化
        child:setTag(i);

        if info.type == "camp" then
            self:initCampItem(child, info);
        elseif info.type == "gem" then
            self:initGemItem(child, info);
        else
            self:initMoneyItem(child, info);
        end

        self.scrollview:addChild(child);
        table.insert(self.items, child);
    end

    if self.showEffect then
        local list = {};
        for j = #self.items, 1, -1 do
            table.insert(list, self.items[j]);
        end

        self.showEffect = false;
        commonScrollItemFlyIn(list);
    end
end

-- 绘制阵营单项
function UITankUse:initCampItem(node, info)
    -- 标题颜色
    local color;
    if info.campId == 1 then
        color = TextStyleM.TEXT_COLOR_LIGHT_GREEN;
    elseif info.campId == 2 then
        color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;
    elseif info.campId == 3 then
        color = TextStyleM.TEXT_COLOR_LIGHT_YELLOW;
    else
        color = TextStyleM.TEXT_COLOR_LIGHT_RED;
    end

    -- 设置标题
    local titleLabel = findChildByName(node, "title_label");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, color, true, -1, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(titleLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(titleLabel, 1, TEXT_OUTLINE_COLOR, true);
    titleLabel:setString(getLocStr("camp_title_1_" .. info.campId));

    -- 设置描述
    local descLabel = findChildByName(node, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, false);

    -- 当前阵营有没有可以抽取的
    local setType = FormulaM.invoke("CALC_POT_PET_RANGE", "gem");
    local slimeList = {};
    for _, slimeType in pairs(setType) do
        slimeList = table.append(slimeList, PetM.getTypeSlimeListByCamp(info.campId, slimeType));
    end

    local slimeNum = #slimeList;
    applyString(descLabel, string.format(getLocStr("camp_desc"), slimeNum));

    -- 设置icon
    local icon = findChildByName(node, "camp_icon");
    icon:loadTexture(getCampIconPath2(info.campId));

    -- 检查有没有可以领奖的
    local rewardIcon = findChildByName(node, "reward");
    local canTakeNum = PetShopM.takePotUseBonusNum(info.campId);
    if canTakeNum > 0 then
        local hint = findChildByName(node, "hint");
        hint:setVisible(true);
        self:checkHint(hint, canTakeNum);
    end

    local canFetch = true;
    -- -- 当前阵营有没有可以抽取的
    -- local canFetch = false;
    -- local setType = FormulaM.invoke("CALC_POT_PET_RANGE");
    -- for _, perType in pairs(setType) do
    --     if #PetM.getFetchSlimeList(info.campId, perType, false) > 0 then
    --         canFetch = true;
    --         break;
    --     end
    -- end

    if info.campId and not canFetch then
        -- 阵营没有可以抽取的
        self:setGray(node);
    else
        self:registerItemClick(node, info);
    end
end

-- 绘制黄金罐单项
function UITankUse:initGemItem(node, info)
    -- 标题颜色
    local color = TextStyleM.TEXT_COLOR_LIGHT_YELLOW;

    -- 设置标题
    local titleLabel = findChildByName(node, "title_label");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, color, true, -1, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(titleLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(titleLabel, 1, TEXT_OUTLINE_COLOR, true);
    titleLabel:setString(getLocStr("camp_title_2_" .. info.index));

    -- 设置标题图标
    local titleIcon = findChildByName(node, "title_icon");
    titleIcon:setVisible(true);
    titleIcon:loadTexture(getCampIconPath2("1512"));
    titleIcon:setPosition(titleLabel:getPositionX() + titleLabel:getVirtualRenderer():getContentSize().width + 20, titleLabel:getPositionY());

    -- 设置描述
    local descLabel = findChildByName(node, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, false);
    applyString(descLabel, getLocStr("camp_desc_2_" .. info.index));

    -- 设置icon
    local icon = findChildByName(node, "camp_icon");
    if info.campId then
        icon:loadTexture(getCampIconPath2(info.campId));
    end

    local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "gem");
    if classId and ItemM.getAmount(ME.user, classId) < info.useNum then
        -- 不够使用
        self:setGray(node);
        self:registerItemClick2(node, info);
    else
        -- 注册每一项点击事件
        self:registerItemClick(node, info);
    end
end

-- 绘制冈布奥单项
function UITankUse:initMoneyItem(node, info)
    -- 标题颜色
    local color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;

    -- 设置标题
    local titleLabel = findChildByName(node, "title_label");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, color, true, -1, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(titleLabel, cc.size(-0.3, -2.8), TextStyleM.TEXT_COLOR_YELLOW_BROWN);
    TextStyleM.setOutlineStyle(titleLabel, 1, TEXT_OUTLINE_COLOR, true);
    titleLabel:setString(getLocStr("camp_title_3_" .. info.index));

    -- 设置标题图标
    local titleIcon = findChildByName(node, "title_icon");
    titleIcon:setVisible(true);
    titleIcon:loadTexture(getCampIconPath2("1511"));
    titleIcon:setPosition(titleLabel:getPositionX() + titleLabel:getVirtualRenderer():getContentSize().width + 20, titleLabel:getPositionY());

    -- 设置描述
    local descLabel = findChildByName(node, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, false);
    applyString(descLabel, getLocStr("camp_desc_3_" .. info.index));

    -- 设置icon
    local icon = findChildByName(node, "camp_icon");
    icon:loadTexture(getCampIconPath2("camp_four"));

    self:registerItemClick(node, info);

    local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", "money");
    if classId and ItemM.getAmount(ME.user, classId) < info.useNum then
        -- 不够使用
        self:setGray(node);
        self:registerItemClick2(node, info);
    else
        -- 注册每一项点击事件
        self:registerItemClick(node, info);
    end
end

-- 注册罐子不够的时候点击事件
function UITankUse:registerItemClick2(node, info)
    local bg = node:getChildByName("bg");

    local function onClickBg(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            node:runAction(cc.ScaleTo:create(0.1, 0.97));
        elseif eventType == ccui.TouchEventType.canceled then
            node:runAction(cc.ScaleTo:create(0.1, 1));
        elseif eventType == ccui.TouchEventType.ended then
            node:runAction(cc.ScaleTo:create(0.1, 1));
            -- 打开购买界面
            local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", info.type);
            local uiform = UIBuyPuzzles.create(classId, info.type);
            UIMgr.getCurrentScene():addForm(uiform);
        end
    end
    AddTouchEventListener(bg, onClickBg);
end

-- 显示/隐藏底部BUTTON
function UITankUse:showBottomBotton(visible)
    local BT = findChildByName(self.node, "BT");
    BT:setVisible(visible);
end

-- 设置图标和背景为灰色
function UITankUse:setGray(node)
    local bg = findChildByName(node, "bg");
    local bgMask = findChildByName(node, "bg_mask");
    local campIcon = findChildByName(node, "camp_icon");
    local campMask = findChildByName(node, "camp_mask");
    local titleIcon = findChildByName(node, "title_icon");
    local titleLabel = findChildByName(node, "title_label");
    local descLabel = findChildByName(node, "desc");
    local nodeArr = {bg, bgMask, campIcon, campMask, titleIcon};

    for _, setNode in ipairs(nodeArr) do
        setGrayTransMode(setNode, true);
    end

    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_GRAY2, false);
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_GRAY2, true, -1, nil, nil, nil, nil, true);
end

-- 注册每一项点击事件
function UITankUse:registerItemClick(node, info)
    local bg = node:getChildByName("bg");

    local function onClickBg(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            node:runAction(cc.ScaleTo:create(0.1, 0.97));
        elseif eventType == ccui.TouchEventType.canceled then
            node:runAction(cc.ScaleTo:create(0.1, 1));
        elseif eventType == ccui.TouchEventType.ended then
            node:runAction(cc.ScaleTo:create(0.1, 1));
            if info.type == "camp" then
                -- 阵营
                self.campId = info.campId;
                self.tankType = "gem";
                -- 重绘界面
                self.showEffect = true;
                self:redraw();
                FormEffectM.btPopUpFromBottom(self);
            elseif info.type == "money" then
                -- 使用普通罐子
                self:waitResultFun();
                Operation.cmd_use_puzzle_box("money", info.useNum);
            elseif info.type == "gem" then
                -- 获取阵营稀有冈布奥
                local setType = FormulaM.invoke("CALC_POT_PET_RANGE", "gem");
                local slimeList = {};
                for _, slimeType in pairs(setType) do
                    slimeList = table.append(slimeList, PetM.getFetchSlimeList(info.campId, slimeType, true));
                end

                -- 当前剩余没有关闭
                if #slimeList <= 0 then
                    alert(getLocStr("scrap_limit_set_tip"));
                    return;
                end
                -- 使用黄金罐子
                self:waitResultFun();
                Operation.cmd_use_puzzle_box("gem", info.useNum, info.campId);
            end
        end
    end
    AddTouchEventListener(bg, onClickBg);
end

-- 播放使用效果
function UITankUse:playBonusEffect(bonusList, puzzleType)
    -- 标记现在在播放效果
    self.bonusEffect = true;
    self.isPlayingEffect = true;

    -- 标题/按钮/内容隐藏
    self:redrawBonus(puzzleType);

    -- 播放效果
    local tankNode = findChildByName(self.node, "CT/tank_node");
    tankNode:removeAllChildren();
    tankNode:setVisible(true);

    local totalNum = #bonusList;
    local posArr;

    -- 清空额外奖励
    self.extraBonus = {};
    -- 清空奖励节点
    self.bonusItemList = {};

    if #bonusList == 1 then
        -- 使用一个
        posArr = PredefinedPos[1];
    elseif #bonusList == 4 then
        posArr = PredefinedPos[5];
    else
        -- 使用五个
        posArr = PredefinedPos[3];
    end

    -- 播放奖励效果
    for index, bonus in pairs(bonusList) do
        local classId = bonus[2];
        local node = cc.Node:create();
        node:setPosition(posArr[index]);
        tankNode:addChild(node);

        -- 罐子图片
        local tankClassId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", puzzleType);

        local tankImage = ccui.ImageView:create(getItemIconPath(ItemM.query(tankClassId, "icon")));
        node.tankImage = tankImage;
        node.tankImage:setScale(1.4);
        node:addChild(tankImage);

        -- 播放碎片光效（数量修正成原本数量）
        local oriNum = bonus[3];
        if bonus[4] >= 0 then
            oriNum = bonus[3] - bonus[4];
        end

        if #bonusList >= 1 and bonus[3] > oriNum then
            self.extraBonus = self.extraBonus or {};
            table.insert(self.extraBonus, {node, oriNum, bonus[3] - oriNum});
        end
        self:playScrapEffect(node, classId, oriNum, index, totalNum);
    end
end

-- 播放碎片弹出效果
function UITankUse:playScrapEffect(node, classId, num, index, totalNum)
    -- 物品图标
    local icon = ItemM.query(classId, "icon");
    local image = ccui.ImageView:create(getItemIconPath(icon));
    local oriScale = image:getScale();
    image:setScale(0);
    image:setOpacity(0);
    image:setPositionY(image:getPositionY() + 5);

    -- 物品格子
    local itemNode = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsIcon.csb");
    local goodIcon = itemNode:getChildByName("goods_icon");
    local moneyIcon = itemNode:getChildByName("money_icon");
    local nameLabel = itemNode:getChildByName("money_count");
    local soldOut = itemNode:getChildByName("sold_out");
    local itemCount = itemNode:getChildByName("item_count");

    local bg = itemNode:getChildByName("bg");
    -- 奖励点击处理
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local bonus = {1, classId, num};
            showBonusDesc(bonus);
        end
    end);
    local kerning = -1;
    if getLang() == "zh" or getLang() == "tw" then
        kerning = -3;
    end
    goodIcon:loadTexture(getItemIconPath(icon));
    moneyIcon:setVisible(false);
    soldOut:setVisible(false);
    goodIcon:setVisible(false);

    nameLabel:setString(ItemM.query(classId, "name"));
    -- 文字居中
    nameLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
    nameLabel:setAnchorPoint(0.5, 0.5);
    nameLabel:setPositionY(nameLabel:getPositionY() + 5);
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BRIGHT_GREEN, nil, kerning, nil, nil, 8);
    itemCount:setPosition(cc.p(itemCount:getPositionX() - 2, itemCount:getPositionY() - 2));
    TextStyleM.setTextStyle(itemCount, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
    itemCount:setString(num);

    local function callback()
        if not node.animaNode then
            local effectNode = cc.Node:create();
            node.effectNode = effectNode;
            node:addChild(effectNode);
            -- 罐子抖动效果
            if self.tankType == "gem" or self.tankType == "pet_camp_card" then
                -- 黄金罐子
                playEffect(effectNode, 1279, 0, 135);
            else
                -- 普通罐子
                playEffect(effectNode, 1282, 0, 135);
            end
            node.tankImage:setVisible(false);
        end

        local function delay1()
            local scaleUp = cc.ScaleTo:create(0.3, oriScale * 1.3);
            local scaleDown = cc.ScaleTo:create(0.1, oriScale);
            local fadeIn = cc.FadeIn:create(0.4);
            local delayTime = 1.0;
            local imageDelay = 0.4;

            -- 闪光光效
            playEffect(node.effectNode, 1281, 0, 0, nil);
            -- 碎片弹出
            node.effectNode:setLocalZOrder(-1);
            local delay = cc.DelayTime:create(imageDelay);
            image:runAction(cc.Sequence:create(delay, scaleUp, scaleDown));
            image:runAction(fadeIn);

            local function delay2()
                itemNode:setVisible(true);
                if index == totalNum then
                    -- 最后一个了
                    self:clickJumpTo();
                end
            end

            -- 出现物品框
            performWithDelay(node, delay2, delayTime);
        end
        performWithDelay(node, delay1, 0.8);
    end

    itemNode:setVisible(false);
    node.imageNode = image;
    node.itemNode = itemNode;
    node:addChild(itemNode);
    node:addChild(image);

    -- 加入
    self.bonusItemList = self.bonusItemList or {};
    table.insert(self.bonusItemList, node);

    performWithDelay(node, callback, (index - 1) * 0.3 + 0.5);
end

-- 点击跳过按钮
function UITankUse:clickJumpTo()
    self.bonusItemList = self.bonusItemList or {};
    self.isPlayingEffect = false;

    local btnBack = findChildByName(self.node, "BT/btn_back");
    btnBack:setTitleText(getLocStr("btn_text_back"));

    for _, node in pairs(self.bonusItemList) do
        node:stopAllActions();
        node.imageNode:stopAllActions();
        node.itemNode:stopAllActions();
        node.imageNode:setVisible(true);
        node.itemNode:setVisible(true);
        node.imageNode:setOpacity(255);
        node.imageNode:setScale(1);

        -- 罐子图片
        if node.tankImage then
            node.tankImage:setVisible(false);
        end

        -- 特效节点
        if node.effectNode then
            node.effectNode:stopAllActions();
            node.effectNode:setVisible(false);
        end
    end

    -- 额外奖励效果
    for _, extraInfo in pairs(self.extraBonus) do
        local node = extraInfo[1];
        local oriNum = extraInfo[2];
        local addNum = extraInfo[3];
        local itemNode = node.itemNode;
        local itemIcon = itemNode:getChildByName("goods_icon");
        itemIcon:setVisible(true);
        node.imageNode:setVisible(false);
        local itemCount = itemNode:getChildByName("item_count");
        -- 提高数字Label的层级
        itemCount:setLocalZOrder(10);
        TextStyleM.setTextStyle(itemCount, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, -2);
        itemCount:setString(string.format(getLocStr("value_add"), oriNum, addNum));
        local scaleUp = cc.ScaleTo:create(0.3, 1 * 1.5);
        local scaleDown = cc.ScaleTo:create(0.2, 1);
        itemIcon:runAction(cc.Sequence:create(scaleUp, scaleDown));
        if not node.effect then
            playEffect(itemNode, 1265, 0, 7);
        end
    end

    -- 领取月卡只要播放奖励效果
    if self.tankType == "pet_camp_card" then
        return;
    end
    -- 弹出再次使用
    local btnDesc = findChildByName(self.node, "BT/btn_buy_gem");
    local hintNode = findChildByName(self.node, "BT/btn_buy_gem/hint");

    self:scaleUpEffect(btnDesc);

    self.useNum = #self.bonusItemList;
    btnDesc:setBright(true);
    btnDesc:setTouchEnabled(true);

    btnDesc:setTitleText(string.format(getLocStr("btn_text_open_more"), self.useNum));
    hintNode:setVisible(false);
end

-- 播放弹出效果
function UITankUse:scaleUpEffect(node)
    local scaleUp = cc.ScaleTo:create(0.2, 1.2);
    local scaleDown = cc.ScaleTo:create(0.1, 1);
    local delay = cc.DelayTime:create(0.1);
    node:setVisible(true);
    node:setScale(0.01);
    node:runAction(cc.Sequence:create(delay, scaleUp, scaleDown));
end

-- 标题/按钮/内容隐藏
function UITankUse:redrawBonus(puzzleType)
    local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", puzzleType);
    local name = ItemM.query(classId, "name");

    if self.tankType == "pet_camp_card" then
        name = getLocStr("magic_cabrite_title");
    end

    -- 主/副标题
    local titleLabel = findChildByName(self.node, "TOP/title_node/title");
    local subheadLabel = findChildByName(self.node, "TOP/title_node/subhead");

    TextStyleM.setArtWordTitleStyle(titleLabel);
    titleLabel:setString(name);

    -- 更新数量
    local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", self.tankType);
    local num = ItemM.getAmount(ME.user, classId);
    subheadLabel:setString(string.format(getLocStr("own_tank_num"), num));

    -- 描述按钮
    local btnDesc = findChildByName(self.node, "BT/btn_buy_gem");
    btnDesc:setVisible(false);

    -- 设置按钮
    local btnSet = findChildByName(self.node, "BT/btn_set");
    btnSet:setVisible(false);

    self.scrollview:setVisible(false);
end

-- 检查是有可领取奖励
function UITankUse:checkHint(hint, para)
    local valLabel = findChildByName(hint, "text");
    TextStyleM.setTextStyle(valLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true);
    valLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);

    if type(para) == "number" then
        if para > 0 then
            hint:setVisible(true);
            valLabel:setVisible(true);
            valLabel:setString(tostring(para));
            playBubbleAnima(hint, false, 1);
        else
            hint:setVisible(false);
        end

    elseif type(para) == "boolean" then
        if para then
            hint:setVisible(true);
            hint:loadTexture("images/ui/main/hint2.png", 1);
            valLabel:setVisible(false);
            playBubbleAnima(hint, false, 1);
        else
            hint:setVisible(false);
        end
    end
end

-- 注册事件处理回调函数
function UITankUse:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UITankUse", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UITankUse" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            self:showBottomBotton(true);
        elseif para["lose"] == "UITankUse" then
            self:showBottomBotton(false);
        end
    end);

    -- 使用罐子事件回调
    EventMgr.register("UITankUse", event.USE_PUZZLE_BOX, function(args)
        local puzzleType = args.type;
        self.waitResult = false;
        UIMgr.getCurrentScene():removeFormByName("UIInvisibleForm");
        closeCommunicatingForm();
        if args.result == 1 then
            -- 播放效果
            local bonusList = args.bonus;
            self:playBonusEffect(bonusList, puzzleType);
        else
            -- 使用失败
            local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", puzzleType);
            local itemName = ItemM.query(classId, "name");
            local msg = string.format(getLocStr("use_pot_fail"), itemName);
            alert(msg);
        end
    end);

    -- 购买罐子事件回调
    EventMgr.register("UITankUse", event.BUY_PUZZLE_BOX, function(args)
        if args.puzzleType ~= self.tankType then
            -- 不是当前的类型
            return;
        end
        if self.bonusEffect then
            local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", args.puzzleType);
            -- 副标题
            local subheadLabel = findChildByName(self.node, "TOP/title_node/subhead");
            -- 更新数量
            local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", args.puzzleType);
            local num = ItemM.getAmount(ME.user, classId);
            subheadLabel:setString(string.format(getLocStr("own_tank_num"), num));
        else
            self:redraw();
        end
    end);

    -- 关注领取奖励的回调
    EventMgr.register("UITankUse", event.TAKE_GOLDEN_POT_BONUS, function(args)
        self:updateBonusBubble();
    end);

    -- 领取佣兵营地月卡奖励
    EventMgr.register("UITankUse", event.TAKE_CAMP_CARD_RET, function(args)
        local puzzleType = args.card_type;
        self.waitResult = false;
        UIMgr.getCurrentScene():removeFormByName("UIInvisibleForm");
        closeCommunicatingForm();

        if args.result == 1 then
            -- 播放效果
            local bonusList = args.bonus;

            -- 将奖励按阵营排序下依次为奥鲁维之刃、卡纳斯的启示、游荡者之歌、深渊的咆哮
            local campOrder = {2, 1, 3, 4};
            local function sortByCamp(item1, item2)
                local classId1 = item1[2];
                local classId2 = item2[2];

                local petId1 = PetM.getPetidByPieceid(classId1);
                local petId2 = PetM.getPetidByPieceid(classId2);

                local campId1 = CampM.getPetCamp(petId1);
                local campId2 = CampM.getPetCamp(petId2);

                local index1 = table.indexOf(campOrder, campId1);
                local index2 = table.indexOf(campOrder, campId2);

                if index1 < index2 then
                    return true;
                else
                    return false;
                end
            end

            table.sort(bonusList, sortByCamp);

            self:playBonusEffect(bonusList, puzzleType);
        else
            -- 领取失败
            local msg = getLocStr("take_pet_camp_bonus_fail");
            alert(msg);

            UIMgr.getCurrentScene():removeFormByName("UITankUse");
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UITankUse 界面析构清理");
            EventMgr.removeAll("UITankUse");
        elseif eventType == "enter" then
            -- 预加载资源
            cc.SpriteFrameCache:getInstance():addSpriteFrames("images/effect_anim/open_toy_egg.plist");
            cc.SpriteFrameCache:getInstance():addSpriteFrames("images/effect_anim/open_toy_egg_normal.plist");
        end
    end);
end

-- 注册点击事件
function UITankUse:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local bg = findChildByName(self.node, "bg");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            local uiPetRecruit = UIMgr.getCurrentScene():getFormByName("UIPetRecruit");
            if uiPetRecruit then
                -- 从招募界面打开的，直接关闭
                UIMgr.getCurrentScene():removeFormByName("UITankUse");
                return;
            end

            local uiGainItemPath = UIMgr.getCurrentScene():getFormByName("UIGainItemPath");
            if uiGainItemPath then
                -- 从获得路径打开，直接关闭
                UIMgr.getCurrentScene():removeFormByName("UITankUse");
                return;
            end

            if self.tankType == "pet_camp_card" then
                -- 月卡播放效果，直接关闭
                UIMgr.getCurrentScene():removeFormByName("UITankUse");
                return;
            end

            if self.isPlayingEffect then
                -- 跳过动画
                self:clickJumpTo();
            elseif self.bonusEffect then
                -- 从特效界面返回
                self.bonusEffect = false;
                self.useNum = nil;
                self:redraw();
                FormEffectM.btPopUpFromBottom(self);
            elseif self.tankType == "gem" then
                -- 回到阵营选择
                self.tankType = "camp";
                self.campId = nil;
                self.showEffect = true;
                self.useNum = nil;
                self:redraw();
                FormEffectM.btPopUpFromBottom(self);
            else
                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UITankUse");
            end
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 点击背景执行跳过
    local function onBgClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            if self.isPlayingEffect then
                -- 跳过动画
                self:clickJumpTo();
            end
        end
    end
    bg:addTouchEventListener(onBgClick);
    self.scrollview:addTouchEventListener(onBgClick);

    -- 说明按钮
    local btnDesc = findChildByName(self.node, "BT/btn_buy_gem");
    local function onDescClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local classId;
            if self.tankType ~= "camp" and not self.useNum then
                if self.tankType ~= "gem" then
                    -- 说明界面
                    UIMgr.getCurrentScene():removeFormByName("UITankDesc")
                    local uiForm = UITankDesc.create(self.tankType, self.campId);
                    UIMgr.getCurrentScene():addForm(uiForm);
                else
                    -- 领奖界面
                    UIMgr.getCurrentScene():removeFormByName("UIGoldenPotBonus")
                    local uiForm = UIGoldenPotBonus.create(self.campId);
                    UIMgr.getCurrentScene():addForm(uiForm);
                end
                AudioM.playFx("button_spell");
            elseif self.tankType ~= "camp" and self.useNum then
                local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", self.tankType);
                if ItemM.getAmount(ME.user, classId) < self.useNum then
                    -- 碎片不足/弹出罐子购买界面
                    local uiform = UIBuyPuzzles.create(classId, self.tankType);
                    UIMgr.getCurrentScene():addForm(uiform);
                    return;
                end
                -- 再次使用按钮
                btnDesc:setVisible(false);
                btnDesc:setTouchEnabled(false);

                self:waitResultFun();
                if self.tankType == "gem" then
                    -- 黄金罐
                    Operation.cmd_use_puzzle_box("gem", self.useNum, self.campId);
                else
                    -- 普通罐子
                    Operation.cmd_use_puzzle_box("money", self.useNum);
                end
                self.useNum = nil;
            elseif self.tankType == "camp" then
                 -- 说明界面
                 UIMgr.getCurrentScene():removeFormByName("UITankDesc")
                 local uiForm = UITankDesc.create("gem");
                 UIMgr.getCurrentScene():addForm(uiForm);
            end
        end
    end
    btnDesc:addTouchEventListener(onDescClick);
    TextStyleM.setTextStyle(btnDesc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnDesc:setTitleText(getLocStr("btn_text_help"));

    -- 设置按钮
    local btnSet = findChildByName(self.node, "BT/btn_set");
    local function onSetClick(sender, eventType)
        if eventType ==  ccui.TouchEventType.ended then
            -- 打开设置界面
            AudioM.playFx("button_click");
            require "game/ui/form/shop/UIPetScrapSet";
            UIMgr.getCurrentScene():removeFormByName("UIPetScrapSet");
            local uiForm = UIPetScrapSet.create(self.campId);
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end
    btnSet:addTouchEventListener(onSetClick);
    TextStyleM.setTextStyle(btnSet, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnSet:setTitleText(getLocStr("btn_text_choose"));
end

-- 等待结果
function UITankUse:waitResultFun()
    self.waitResult = true;
    wait(1);
    local function delay()
        if self.waitResult then
            -- 结果还没到，显示加载中
            showCommunicatingForm(getLocStr("loading"));
        end
    end
    performWithDelay(self.node, delay , 0.8);
end

-- 领取月卡奖励的时候直接打开的
function UITankUse:redrawPetCampCard()
    local titleNode = findChildByName(self.node, "TOP/title_node");
    local titleLabel = findChildByName(titleNode, "title");
    local subheadLabel = findChildByName(titleNode, "subhead");

    -- 主标题颜色
    local color = TextStyleM.TEXT_COLOR_LIGHT_YELLOW;

    -- 主标题
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, color, true, -1, nil, nil, nil, nil, true);
    local titleName = getLocStr("magic_cabrite_title");
    titleLabel:setString(titleName);

    self:waitResultFun();
end